<?php
namespace app\index\controller;
use think\Session;
use think\Controller;
use think\Db;
class Article extends Controller
{
    public function changelog()
    {
        return view('changelog');
    }
    public function List(){
    	if (session("login")!=1) return $this->error("请先登录");
    	$result=Db::query("SELECT article_id,title,time,hit,nikename FROM article a left join admin b on a.author_id = b.id");
    	$this->assign("arr",$result);
        return $this->fetch("list");
    }
    public function Add(){
    	if (session("login")!=1) return $this->error("请先登录");
    	if (isset($_POST["addArticle"])) {
    		$file = request()->file('cover_img');
            if($file){
                $info = $file->rule("md5")->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    //windows
                    $photoStr="/uploads/".str_replace('\\','/',$info->getSaveName());
                    //linux
                    //$photoStr="/uploads/".$info->getSaveName();    
                }else{
                    $photoStr="";
                    return "图片上传失败！";
                }
            }
    		$add=[
                "title"=>input("title"),
                "author_id"=>session('uid'),
                "cover_img"=>$photoStr,
                "desp"=>$_POST['desp'],
                "time"=>date("Y-m-d H:i:s"),
                "content"=>$_POST['content'],
                "hit"=>0
            ];
    		$result=db('article')->insertGetId($add);
            if($result) return $this->success('添加成功');
            else return $this->error('添加失败');
    	}else return $this->fetch("add");
    }
    public function Del(){
    	if (session("login")!=1) return $this->error("请先登录");
    	$result=db('article')->where('article_id',input("id"))->delete();
    	if($result==1) return $this->success('删除成功');
    	else return $this->error('删除失败');
    }
    public function Edit(){
    	if (session("login")!=1) return $this->error("请先登录");
    	if (isset($_POST["EditArticle"])) {
    		
    		$data=[
                "title"=>input("title"),
                "author_id"=>session('uid'),
                "desp"=>$_POST['desp'],
                "time"=>date("Y-m-d H:i:s"),
                "content"=>$_POST['content']
            ];
    		$result=db('article')->where("article_id",input("id"))->update($data);
            if($result) return $this->success('修改成功');
            else return $this->error('修改失败');
            
    	}else {
    		$article=db("article")->where("article_id",input("id"))->find();
    		$this->assign("a",$article);
    		return $this->fetch("edit");
    	}
    }
}


